import { Column, Entity, ManyToOne, Index } from 'typeorm';
import { BaseEntity } from '../../../common/entities/base.entity';
import { User } from '../../user/entities/user.entity';
import { Novel } from './novel.entity';
import { NovelChapter } from './novel-chapter.entity';

@Entity('user_reading_history')
@Index(['userId'], { unique: false })
@Index(['novelId'], { unique: false })
@Index(['userId', 'novelId'], { unique: true })
export class UserReadingHistory extends BaseEntity {
  @Column({ type: 'bigint', comment: '用户ID' })
  userId: number;

  @Column({ type: 'bigint', comment: '小说ID' })
  novelId: number;

  @Column({ type: 'bigint', nullable: true, comment: '章节ID' })
  chapterId: number;

  @Column({ type: 'int', default: 0, comment: '阅读位置(字符数)' })
  readPosition: number;

  @Column({
    type: 'decimal',
    precision: 5,
    scale: 2,
    default: 0.0,
    comment: '阅读进度百分比',
  })
  readProgress: number;

  @Column({
    type: 'datetime',
    default: () => 'CURRENT_TIMESTAMP',
    comment: '最后阅读时间',
  })
  lastReadAt: Date;

  // 关联关系
  @ManyToOne(() => User, (user) => user.readingHistory, { onDelete: 'CASCADE' })
  user: User;

  @ManyToOne(() => Novel, (novel) => novel.readingHistory, {
    onDelete: 'CASCADE',
  })
  novel: Novel;

  @ManyToOne(() => NovelChapter, (chapter) => chapter.readingHistory, {
    onDelete: 'SET NULL',
    nullable: true,
  })
  chapter: NovelChapter;
}
